import { NavBar, InfiniteScroll } from "antd-mobile";
import { useHistory, useParams } from "react-router-dom";
import classNames from "classnames";
import styles from "./index.module.scss";

import Icon from "@/components/Icon";
import CommentItem from "./components/CommentItem";
import CommentFooter from "./components/CommentFooter";
import { getArticleInfo, getCommentList } from "@/store/actions/article";
import dayjs from "dayjs";
import useInitialState from "@/utils/use-initial-state";
import DOMPurify from "dompurify";
import hljs from "highlight.js";
import "highlight.js/styles/vs2015.css";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/types/store";
const Article = () => {
  const history = useHistory();
  const Params = useParams<{ id: string }>();
  // 获取动态路由参数
  const articleId = Params.id;
  // 获取文章详情信息
  const { info } = useInitialState(() => getArticleInfo(articleId), "article");
  useEffect(() => {
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    });
    // 获取到内容中所有的code标签
    const codes = document.querySelectorAll(".dg-html pre code");
    codes.forEach((el) => {
      // 让code进行高亮
      hljs.highlightElement(el as HTMLElement);
    });
  }, [info]);
  // 获取评论数据
  const { comment } = useInitialState(() => getCommentList(articleId), "article");
  // 是否显示顶部信息
  const [isShowAuthor, setIsShowAuthor] = useState(false);
  const authorRef = useRef<HTMLDivElement>(null);
  const wrapRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const wrapDOM = wrapRef.current!;
    const authDOM = authorRef.current!;
    const onScroll = function () {
      const rect = authDOM.getBoundingClientRect()!;
      console.log(rect.top, "rect.top==============================================================================");

      if (rect.top <= 0) {
        setIsShowAuthor(true);
      } else {
        setIsShowAuthor(false);
      }
    };
    wrapDOM.addEventListener("scroll", onScroll);
    return () => {
      wrapDOM.removeEventListener("scroll", onScroll);
    };
  }, []);

  // 获取评论数据
  const { results = [], total_count = -1, last_id, end_id = "" } = useSelector((state: RootState) => state.article.comment);

  const hasMore = last_id !== end_id;
  const dispatch = useDispatch();
  const loadMore = async () => {
    // console.log('加载更多数据')
    await dispatch(getCommentList(articleId));
  };
  const renderArticle = () => {
    // 文章详情
    return (
      <div className="wrapper" ref={wrapRef}>
        <div className="article-wrapper">
          <div className="header">
            <h1 className="title">{info.title}</h1>

            <div className="info">
              <span>{dayjs(info.pubdate).format("YYYY-MM-DD")}</span>
              <span>{info.read_count} 阅读</span>
              <span>{info.comm_count} 评论</span>
            </div>

            <div className="author" ref={authorRef}>
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span className={classNames("follow", info.is_followed ? "followed" : "")}>{info.is_followed ? "已关注" : "关注"}</span>
            </div>
          </div>

          <div className="content">
            <div className="content-html dg-html" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(info.content || "") }} />
            <div className="date">发布文章时间：{dayjs(info.pubdate).format("YYYY-MM-DD")}</div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span className="gengduoicon">
              <Icon type="icon-gengduo-2" />
            </span>
          }
        >
          {isShowAuthor && (
            <div className="nav-author">
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span className={classNames("follow", info.is_followed ? "followed" : "")}>{info.is_followed ? "已关注" : "关注"}</span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}
        <div className="comment-list">{info.comm_count === 0 ? <p>没有更多评论</p> : comment.results?.map((item) => <CommentItem key={item.com_id} type="normal" comment={item}></CommentItem>)}</div>

        <InfiniteScroll hasMore={hasMore} loadMore={loadMore}></InfiniteScroll>
        {/* 底部评论栏 */}
        <CommentFooter />
      </div>
    </div>
  );
};

export default Article;
